package com.zjy.weather.util

import android.content.Context
import android.content.res.ColorStateList
import android.content.res.Resources
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.View

/**
 * Created by wiikii on 16/11/3.
 * Copyright (C) 2014 wiikii. All rights reserved.
 */
object UIUtils {

    val screenWidth: Int
        get() = Resources.getSystem().displayMetrics.widthPixels

    val screenHeight: Int
        get() = Resources.getSystem().displayMetrics.heightPixels

    fun dip2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    fun px2dip(context: Context, pxValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (pxValue / scale + 0.5f).toInt()
    }

    fun sp2px(context: Context, spValue: Float): Int {
        val fontScale = context.resources.displayMetrics.scaledDensity
        return (spValue * fontScale + 0.5f).toInt()
    }

    fun getViewWidth(view: View): Int {
        val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec((1 shl 30) - 1, View.MeasureSpec.AT_MOST)
        val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec((1 shl 30) - 1, View.MeasureSpec.AT_MOST)
        view.measure(widthMeasureSpec, heightMeasureSpec)

        return view.measuredWidth
    }

    fun getViewHeight(view: View): Int {
        val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec((1 shl 30) - 1, View.MeasureSpec.AT_MOST)
        val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec((1 shl 30) - 1, View.MeasureSpec.AT_MOST)
        view.measure(widthMeasureSpec, heightMeasureSpec)

        return view.measuredHeight
    }

    fun getStringWidth(string: String, textSize: Float): Int {
        val paint = Paint()
        paint.textSize = textSize
        val rect = Rect()
        paint.getTextBounds(string, 0, string.length, rect)
        return rect.width()
    }

    fun getStringHeight(string: String, textSize: Float): Int {
        val paint = Paint()
        paint.textSize = textSize
        val rect = Rect()
        paint.getTextBounds(string, 0, string.length, rect)
        return rect.height()
    }

    fun createColorMaskList(): ColorStateList {
        return createColorStateList(Color.TRANSPARENT, Color.parseColor("#0A000000"))
    }

    fun createColorStateList(normal: Int, pressed: Int): ColorStateList {
        val colors = intArrayOf(pressed, normal)
        val states = arrayOfNulls<IntArray>(2)
        states[0] = intArrayOf(android.R.attr.state_pressed)
        states[1] = intArrayOf()
        return ColorStateList(states, colors)
    }
}
